<template>
  <Row class="w1 h1">
    <Col :span="24" style="margin-bottom:20px;">
      <Button @click="handleUploadImage">配电图上传</Button>
    </Col>
    <Col :span="24">
      <Table :columns="columns" :data="tableData" border> </Table>
    </Col>
    <Modal title="配电图上传" v-model="visible">
      <Form :label-width="100" :model="params" ref="formRef" :rules="rules">
        <FormItem label="配电图名称：" prop="name">
          <Input
            type="text"
            placeholder="配电图名称..."
            v-model.trim="params.name"
          ></Input>
        </FormItem>
        <FormItem label="图片：" :error="uploadImageError">
          <Upload
            ref="upload"
            v-model="params.file"
            :show-upload-list="false"
            :before-upload="handleBeforeUpload"
            type="drag"
            action="//jsonplaceholder.typicode.com/posts/"
            style="display: inline-block;width:58px;"
          >
            <div style="width: 58px;height:58px;line-height: 58px;">
              <Icon type="ios-camera" size="20" />
            </div>
          </Upload>
          <div
            style="width:60px;height:60px;overflow:hidden;display:inline-block;margin-left:10px;"
            v-if="imageSourceUrl"
          >
            <img
              width="100%"
              height="100%"
              :src="imageSourceUrl"
              :alt="params.name"
            />
          </div>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="handleSubmit">确定</Button>
      </div>
    </Modal>
    <Modal
      title="查看图片"
      v-model="imageVisible"
      :footer-hide="true"
      width="732px"
    >
      <div style="width: 700px;height: 500px;">
        <img :src="imageShowUrl" alt="" width="100%" height="100%" />
      </div>
    </Modal>
  </Row>
</template>
<script>
import {
  uploadImagePeiDian,
  getGalleryList,
  genGalleryUrl,
  removeImage,
  yulanImage
} from "@/api";
function getObjectURL(file) {
  let url = null;
  if (window.createObjectURL != undefined) {
    // basic
    url = window.createObjectURL(file);
  } else if (window.URL != undefined) {
    // mozilla(firefox)
    url = window.URL.createObjectURL(file);
  } else if (window.webkitURL != undefined) {
    // webkit or chrome
    url = window.webkitURL.createObjectURL(file);
  }
  return url;
}

export default {
  props: {
    id: {
      type: String,
      default: ""
    }
  },
  mounted() {
    this.getGalleryList();
  },
  watch: {
    id() {
      this.getGalleryList();
    }
  },
  data() {
    const vm = this;
    const validImage = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请选择图片"));
      } else {
        const { size, type } = value;
        if (type.indexOf("image") !== -1) {
          if (size > 5242880) {
            callback(new Error("文件最大不能超过5M"));
          }
          callback();
        } else {
          callback(new Error("只能上传 .jpg、.jpeg、.png、.bmp 类型文件"));
        }
      }
    };
    return {
      params: {
        companyId: "",
        name: "",
        file: null
      },
      visible: false,
      imageSourceUrl: "",
      imageShowUrl: "",
      imageVisible: false,
      columns: [
        {
          title: "配电图名称",
          key: "name",
          align: "center"
        },
        {
          title: "创建时间",
          align: "center",
          render(h, params) {
            const {
              row: { createdAt }
            } = params;
            return h(
              "span",
              vm.moment(createdAt).format("YYYY-MM-DD HH:mm:ss")
            );
          }
        },
        {
          title: "操作",
          align: "center",
          render(h, params) {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      const row = { ...params.row };
                      vm.handleShowImage(row);
                    }
                  }
                },
                "查看"
              ),
              h(
                "Poptip",
                {
                  props: {
                    confirm: true,
                    title: "您确定要删除这条数据吗?",
                    transfer: true,
                    cancelText: "取消"
                  },
                  on: {
                    "on-ok": () => {
                      const row = { ...params.row };
                      vm.handleDelete(row);
                    }
                  }
                },
                [
                  h(
                    "Button",
                    {
                      style: {
                        marginRight: "5px"
                      },
                      props: {
                        type: "error",
                        size: "small"
                      }
                    },
                    "删除"
                  )
                ]
              )
            ]);
          }
        }
      ],
      rules: {
        name: [
          {
            required: true,
            trigger: "blur",
            message: "请输入配电图名称"
          }
        ],
        file: [
          {
            validator: validImage,
            required: true,
            trigger: "change"
          }
        ]
      },
      tableData: [],
      uploadList: [],
      uploadImageError: false
    };
  },
  methods: {
    handleBeforeUpload(file) {
      const formData = new FormData();
      const { type, size } = file;
      if (type.indexOf("image") !== -1) {
        if (size < 5242880) {
          const url = getObjectURL(file);
          this.uploadImageError = false;
          if (url) {
            this.imageSourceUrl = url;
          }
          this.params.file = file;
        } else {
          this.uploadImageError = "文件最大不能超过5M";
          this.imageSourceUrl = "";
        }
      } else {
        this.uploadImageError = "只能上传 .jpg、.jpeg、.png、.bmp 类型文件";
        this.imageSourceUrl = "";
      }

      return false;
    },

    handleUploadImage() {
      this.visible = true;
      this.imageSourceUrl = "";
      this.uploadImageError = false;
      this.$nextTick(() => {
        this.uploadList = this.$refs.upload.fileList;
        const dom = this.$refs.formRef;
        dom.resetFields();
        this.params = {
          companyId: "",
          name: "",
          file: null
        };
      });
    },

    handleSubmit() {
      const vm = this;
      const dom = this.$refs.formRef;

      dom.validate(valid => {
        if (vm.imageSourceUrl) {
          if (valid) {
            const _params = { ...this.params };
            _params.companyId = this.id;
            const keys = Object.keys(_params);
            const formData = new FormData();
            keys.forEach(t => {
              formData.append(t, _params[t]);
            });
            uploadImagePeiDian(formData).then(res => {
              if (res.code === 200) {
                this.visible = false;
                this.$Message.success("操作成功");
                this.getGalleryList();
              }
            });
          }
        } else {
          if (vm.uploadImageError) {
            vm.uploadImageError = vm.uploadImageError;
          } else {
            vm.uploadImageError = "请选择图片";
          }
        }
      });
    },

    handleDelete(row) {
      const { id } = row;
      const params = { id };
      removeImage(params).then(res => {
        if (res.code === 200) {
          this.$Message.success("操作成功");
          this.getGalleryList();
        }
      });
    },

    async handleShowImage(row) {
      const { imgUrl, id } = row;
      // 大众
      this.imageShowUrl = yulanImage(id);

      // yun3
      // this.imageShowUrl = genGalleryUrl(imgUrl)
      this.imageVisible = true;
    },

    getGalleryList() {
      const vm = this;
      const params = { companyId: vm.id };
      getGalleryList(params).then(res => {
        if (res.code === 200) {
          this.tableData = res.data;
        } else {
          this.tableData = [];
        }
      });
    }
  }
};
</script>
